<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <sub-filter @filter-change="changeFilter" />
      <div class="goods-list">
        <!-- 排序 -->
        <sub-sort @sort-change="changeSort" />
        <!-- 列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <goods-item :goods="goods" />
          </li>
        </ul>
        <!-- 加载 -->
        <XtxInfiniteLoading
          :loading="loading"
          :finished="finished"
          @infinite="getData"
        />
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from "./components/sub-bread";
import SubFilter from "./components/sub-filter.vue";
import { ref } from "@vue/reactivity";
import SubSort from "./components/sub-sort.vue";
import GoodsItem from "./components/goods-item.vue";
import { useRoute } from "vue-router";
import { findSubCategoryGoods } from "@/api/category";
import { watch } from "@vue/runtime-core";
export default {
  name: "SubCategory",
  components: { SubBread, SubFilter, SubSort, GoodsItem },
  setup() {
    const loading = ref(false);
    const finished = ref(false);
    const goodsList = ref([]);
    const route = useRoute();
    let reqParams = {
      page: 1,
      pageSize: 20,
    };
    // 获取数据函数
    const getData = () => {
      //  reqParams.categoryId = route.params.id
      loading.value = true;
      findSubCategoryGoods(reqParams).then(({ result }) => {
        if (result.items.length) {
          goodsList.value.push(...result.items);
          reqParams.page++;
        } else {
          // 全部加载完毕
          finished.value = true;
        }
        // 请求结束
        loading.value = false;
      });
    };
    watch(
      () => route.params.id,
      (newVal) => {
        if (newVal && `/category/sub/${newVal}` === route.path) {
          goodsList.value = [];
          reqParams.page = 1;
          finished.value = false;
        }
      }
    );

    // 监听筛选区改变
    const changeFilter = (filterParams) => {
      reqParams = { ...reqParams, ...filterParams };
      reqParams.page = 1;
      goodsList.value = [];
      finished.value = false;
    };
    // 监听排序区改变
    const changeSort = (sortParams) => {
      reqParams = { ...reqParams, ...sortParams };
      reqParams.page = 1;
      goodsList.value = [];
      finished.value = false;
    };
    return { loading, finished, goodsList, getData, changeFilter, changeSort };
  },
};
</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>